package orbitPrototype.event;

import java.util.ArrayList;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import orbitPrototype.Util;

public class EventHandler
{
	private static ArrayList<EventTarget> _eventTargets = new ArrayList<EventTarget>();
	
	public EventHandler()
	{
		
	}
	
	public static void registerEventListener(String event, Object object, String method, boolean targetOnly)
	{
		_eventTargets.add(new EventTarget(event, object, method, targetOnly));
	}
	
	public static void unregisterEventListener(String event, Object object, String method)
	{
		for(int i = 0; i < _eventTargets.size(); i++)
		{
			if(_eventTargets.get(i).getEvent().equals(event) && 
				_eventTargets.get(i).getObject() == object && 
				_eventTargets.get(i).getMethod() == method)
			{
				_eventTargets.remove(i);
				break;
			}
		}
	}
	
	public static void triggerEvent(String event)
	{
		Util.output("GLOBAL event triggered: " + event + "!");
		
		for(EventTarget eventTarget:_eventTargets)
		{
			if(eventTarget.getEvent().equals(event) && !eventTarget.getTargetOnly())
			{
				invokeTriggeredMethod(eventTarget.getObject(), eventTarget.getMethod());
			}
		}
	}
	
	public static void triggerEvent(String event, Object object)
	{
		for(EventTarget eventTarget:_eventTargets)
		{
			if(eventTarget.getEvent().equals(event) && eventTarget.getObject() == object)
			{
				invokeTriggeredMethod(eventTarget.getObject(), eventTarget.getMethod());
			}
		}
	}
	
	public static void invokeTriggeredMethod(Object object, String methodName)
	{
		try
		{
			Method method = object.getClass().getDeclaredMethod(methodName, null);
			method.setAccessible(true);
			
			method.invoke(object, null);
		} 
		catch (NoSuchMethodException e)
		{
			e.printStackTrace();
		} 
		catch (SecurityException e)
		{
			e.printStackTrace();
		} 
		catch (IllegalAccessException e)
		{
			e.printStackTrace();
		} 
		catch (IllegalArgumentException e)
		{
			e.printStackTrace();
		} 
		catch (InvocationTargetException e)
		{
			e.printStackTrace();
		}
	}
	
	public static ArrayList<EventTarget> getEventList()
	{
		return _eventTargets;
	}
	
	
}
